/**
 *
 */
package org.suren.littlebird.server;

import org.apache.cxf.aegis.databinding.AegisDatabinding;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.console.MessageConsoleStream;
import org.suren.littlebird.Activator;
import org.suren.littlebird.console.BundleConsoleFactory;
import org.suren.littlebird.preferences.PreferenceConstants;

/**
 * @author suren
 * @since 2015-2-2
 */
public class LoggerServerFactory
{
	private static LoggerServer server;
	private static ClientProxyFactoryBean factory;
	private static String url;
	private static final IPreferenceStore store = Activator.getDefault().getPreferenceStore();
	private static MessageConsoleStream msgStream = BundleConsoleFactory.getConsole().newMessageStream();

	public static LoggerServer getInstance()
	{
		url = store.getString(PreferenceConstants.P_OSGI_SERVER);
		if(url == null || server == null || factory == null || !factory.getAddress().equals(url))
		{
			factory = getClientProxy();
			server = (LoggerServer) factory.create();
		}
		else
		{
			factory = null;
			server = null;
		}

		return server;
	}

	/**
	 * @return
	 */
	private static ClientProxyFactoryBean getClientProxy()
	{
		int port =store.getInt(PreferenceConstants.P_OSGI_PORT);

		String host = url + ":" + port + "/logger";
		if(!host.startsWith("http://") && !host.startsWith("https://"))
		{
			host = "http://" + host;
		}

		return getClientProxy(host, BundleServer.class);
	}

	/**
	 * @param url
	 * @param clazz
	 * @return
	 */
	private static ClientProxyFactoryBean getClientProxy(String url, Class<BundleServer> clazz)
	{
		ClientProxyFactoryBean factory = new ClientProxyFactoryBean();

		msgStream.println("getClientProxy from " + url);

		factory.setAddress(url);
		factory.setServiceClass(LoggerServer.class);
		factory.getServiceFactory().setDataBinding(new AegisDatabinding());

		return factory;
	}
}
